
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
} from '@/utils/auth'



const state = {
  token: getToken(),
  name: '',
  roles: [],
  permissions: [],
  userInfo: {},
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  login({
    commit
  }, info) {
    setToken(info.token)
    commit('SET_TOKEN', info.token)
    commit('SET_USERINFO', info)
  },

  // 获取用户信息
  GetInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {

        const user = res.data.user
        if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', res.data.roles)
          commit('SET_PERMISSIONS', res.data.permissions)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        commit('SET_NAME', res.data.user.userName)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 前端 登出
  logOut({
    commit
  }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}